import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/delete_book")
public class DeleteBook extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        
        String number = request.getParameter("number");

        if (number == null || number.isEmpty()) {
            response.getWriter().write("{\"status\":\"error\",\"message\":\"Number parameter is required.\"}");
            return;
        }

        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement("DELETE FROM t_book WHERE number = ?")) {
            stmt.setString(1, number);
            int rowsAffected = stmt.executeUpdate();
            if (rowsAffected > 0) {
                response.getWriter().write("{\"status\":\"success\",\"message\":\"Book deleted successfully.\"}");
            } else {
                response.getWriter().write("{\"status\":\"error\",\"message\":\"Book not found.\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\":\"error\",\"message\":\"Error deleting book.\"}");
        }
    }

    private Connection getConnection() throws SQLException {
        String jdbcUrl = "jdbc:mysql://113.44.148.207:3306/linux_exam";
        String jdbcUsername = "root";
        String jdbcPassword = "1qaz@WSX#EDC";
        return DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
    }
}

